import { useState, useEffect, useCallback, useRef } from 'react';
import { socketManager } from '@/services/socket';
import { getUserId } from '@/utils/helpers';

export interface UseSocketReturn {
  // 连接状态
  isConnected: boolean;
  isConnecting: boolean;
  
  // 房间状态
  isInRoom: boolean;
  participants: string[];
  
  // 方法
  connect: () => Promise<void>;
  disconnect: () => void;
  joinRoom: (roomId: string) => Promise<void>;
  leaveRoom: (roomId: string) => void;
  
  // 错误状态
  error: string | null;
}

export const useSocket = (): UseSocketReturn => {
  const [isConnected, setIsConnected] = useState(false);
  const [isConnecting, setIsConnecting] = useState(false);
  const [isInRoom, setIsInRoom] = useState(false);
  const [participants, setParticipants] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);
  
  const userIdRef = useRef<string>(getUserId());
  const currentRoomRef = useRef<string | null>(null);

  // 连接到服务器
  const connect = useCallback(async () => {
    if (isConnected || isConnecting) return;

    setIsConnecting(true);
    setError(null);

    try {
      await socketManager.connect();
      setIsConnected(true);
    } catch (error: any) {
      console.error('Socket 连接失败:', error);
      setError(error.message || 'Socket 连接失败');
    } finally {
      setIsConnecting(false);
    }
  }, [isConnected, isConnecting]);

  // 断开连接
  const disconnect = useCallback(() => {
    socketManager.disconnect();
    setIsConnected(false);
    setIsInRoom(false);
    setParticipants([]);
    currentRoomRef.current = null;
  }, []);

  // 加入房间
  const joinRoom = useCallback(async (roomId: string) => {
    if (!isConnected) {
      await connect();
    }

    try {
      socketManager.joinRoom(roomId, userIdRef.current);
      currentRoomRef.current = roomId;
    } catch (error: any) {
      console.error('加入房间失败:', error);
      setError(error.message || '加入房间失败');
    }
  }, [isConnected, connect]);

  // 离开房间
  const leaveRoom = useCallback((roomId: string) => {
    if (isConnected && currentRoomRef.current === roomId) {
      socketManager.leaveRoom(roomId, userIdRef.current);
      setIsInRoom(false);
      setParticipants([]);
      currentRoomRef.current = null;
    }
  }, [isConnected]);

  // 设置 Socket 事件监听
  useEffect(() => {
    const socket = socketManager.getSocket();
    if (!socket) return;

    // 连接状态事件
    const handleConnect = () => {
      console.log('Socket 连接成功');
      setIsConnected(true);
      setError(null);
    };

    const handleDisconnect = (reason: string) => {
      console.log('Socket 连接断开:', reason);
      setIsConnected(false);
      setIsInRoom(false);
      setParticipants([]);
      
      if (reason === 'io server disconnect') {
        setError('服务器主动断开连接');
      }
    };

    const handleConnectError = (error: Error) => {
      console.error('Socket 连接错误:', error);
      setError('连接服务器失败');
      setIsConnecting(false);
    };

    // 房间事件
    const handleRoomJoined = (data: { roomId: string; participants: string[] }) => {
      console.log('成功加入房间:', data);
      setIsInRoom(true);
      setParticipants(data.participants);
      setError(null);
    };

    const handleUserJoined = (data: { userId: string; roomId: string }) => {
      console.log('用户加入房间:', data);
      if (data.userId !== userIdRef.current) {
        setParticipants(prev => {
          if (!prev.includes(data.userId)) {
            return [...prev, data.userId];
          }
          return prev;
        });
      }
    };

    const handleUserLeft = (data: { userId: string; roomId: string }) => {
      console.log('用户离开房间:', data);
      setParticipants(prev => prev.filter(id => id !== data.userId));
    };

    const handleRoomFull = (data: { roomId: string }) => {
      console.log('房间已满:', data);
      setError('房间已满，无法加入');
      setIsInRoom(false);
    };

    const handleRoomNotFound = (data: { roomId: string }) => {
      console.log('房间不存在:', data);
      setError('房间不存在或已过期');
      setIsInRoom(false);
    };

    // 注册事件监听器
    socket.on('connect', handleConnect);
    socket.on('disconnect', handleDisconnect);
    socket.on('connect_error', handleConnectError);
    
    socketManager.onRoomJoined(handleRoomJoined);
    socketManager.onUserJoined(handleUserJoined);
    socketManager.onUserLeft(handleUserLeft);
    socketManager.onRoomFull(handleRoomFull);
    socketManager.onRoomNotFound(handleRoomNotFound);

    // 清理函数
    return () => {
      socket.off('connect', handleConnect);
      socket.off('disconnect', handleDisconnect);
      socket.off('connect_error', handleConnectError);
      
      socketManager.off('room-joined', handleRoomJoined);
      socketManager.off('user-joined', handleUserJoined);
      socketManager.off('user-left', handleUserLeft);
      socketManager.off('room-full', handleRoomFull);
      socketManager.off('room-not-found', handleRoomNotFound);
    };
  }, []);

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (currentRoomRef.current) {
        socketManager.leaveRoom(currentRoomRef.current, userIdRef.current);
      }
    };
  }, []);

  return {
    isConnected,
    isConnecting,
    isInRoom,
    participants,
    connect,
    disconnect,
    joinRoom,
    leaveRoom,
    error,
  };
};